package com.hotelManager.www.servlet;

import com.hotelManager.www.controller.MerchantController;
import com.hotelManager.www.po.*;
import com.hotelManager.www.common.Result;
import com.hotelManager.www.common.ResultCode;
import com.google.gson.Gson;
import com.hotelManager.www.config.GsonConfig;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 商户端Servlet
 * 处理所有与商户相关的请求
 */
@WebServlet("/merchant/*")
public class MerchantServlet extends HttpServlet {
    private final MerchantController merchantController = new MerchantController();
    private final Gson gson = GsonConfig.getGson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取当前登录的商户用户
            HttpSession session = request.getSession();
            User merchantUser = (User) session.getAttribute("user");
            
            // 获取商户ID
            Integer merchantId = merchantUser.getId();
            Shop shop = merchantController.getShopByUserId(merchantId).getData();
            if (shop == null) {
                response.getWriter().write(gson.toJson(Result.failure(ResultCode.NOT_FOUND, "未找到对应的店铺信息")));
                return;
            }
            Integer shopId = shop.getId();

            switch (pathInfo) {
                case "/shop/info":
                    // 获取店铺信息
                    result.put("success", true);
                    result.put("data", shop);
                    break;

                case "/room/types":
                    // 获取房型列表
                    List<RoomType> roomTypes = merchantController.getRoomTypes(shopId).getData();
                    result.put("success", true);
                    result.put("data", roomTypes);
                    break;

                case "/orders/pending":
                    // 获取待处理订单
                    List<Order> pendingOrders = merchantController.getPendingOrders(shopId).getData();
                    result.put("success", true);
                    result.put("data", pendingOrders);
                    break;

                case "/orders/completed":
                    // 获取已完成订单
                    List<Order> completedOrders = merchantController.getCompletedOrders(shopId).getData();
                    result.put("success", true);
                    result.put("data", completedOrders);
                    break;

                case "/orders/refunding":
                    // 获取退房申请订单
                    List<Order> refundingOrders = merchantController.getRefundingOrders(shopId).getData();
                    result.put("success", true);
                    result.put("data", refundingOrders);
                    break;

                case "/statistics":
                    // 获取销量和营业额
                    Integer salesVolume = merchantController.getSalesVolume(shopId).getData();
                    BigDecimal revenue = merchantController.getRevenue(shopId).getData();
                    result.put("success", true);
                    result.put("data", Map.of(
                        "salesVolume", salesVolume,
                        "revenue", revenue
                    ));
                    break;

                case "/blacklist":
                    // 获取黑名单列表
                    List<UserBlacklist> blacklist = merchantController.getBlacklistByShopId(shopId).getData();
                    result.put("success", true);
                    result.put("data", blacklist);
                    break;

                default:
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        
        response.getWriter().write(gson.toJson(result));
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取当前登录的商户用户
            HttpSession session = request.getSession();
            User merchantUser = (User) session.getAttribute("user");

            // 仅/shop/register允许shop==null
            if ("/shop/register".equals(pathInfo)) {
                System.out.println("[MerchantServlet] 进入/shop/register，允许shop==null，准备注册店铺");
                handleShopRegister(request, response, merchantUser);
                return;
            }

            // 其他操作必须有shop
            Integer merchantId = merchantUser.getId();
            Shop shop = merchantController.getShopByUserId(merchantId).getData();
            if (shop == null) {
                System.out.println("[MerchantServlet] shop为null，拒绝非注册操作: " + pathInfo);
                response.getWriter().write(gson.toJson(Result.failure(ResultCode.NOT_FOUND, "未找到对应的店铺信息")));
                return;
            }
            Integer shopId = shop.getId();

            switch (pathInfo) {
                case "/room/type/add":
                    // 添加房型
                    handleAddRoomType(request, response, shopId);
                    return;


                case "/room/type/delete":
                    // 删除房型
                    handleDeleteRoomType(request, response);
                    return;

                case "/order/verify":
                    // 核销订单
                    handleVerifyOrder(request, response, merchantId);
                    return;

                case "/order/refund/process":
                    // 处理退订申请
                    handleProcessRefund(request, response, shopId);
                    return;

                case "/blacklist/add":
                    // 添加用户到黑名单
                    handleAddToBlacklist(request, response, shopId);
                    return;

                case "/blacklist/remove":
                    // 从黑名单中移除用户
                    handleRemoveFromBlacklist(request, response);
                    return;

                default:
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                    return;
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
            response.getWriter().write(gson.toJson(result));
        }
    }
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 获取当前登录的商户用户
            HttpSession session = req.getSession();
            User merchantUser = (User) session.getAttribute("user");
            // 获取请求路径
            String pathInfo = req.getPathInfo();
            System.out.println("MerchantServlet.doPut] 请求路径: " + pathInfo);
            // 其他操作必须有shop
            Integer merchantId = merchantUser.getId();
            Shop shop = merchantController.getShopByUserId(merchantId).getData();
            if (shop == null) {
                System.out.println("[MerchantServlet] shop为null，拒绝非注册操作: " + pathInfo);
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.NOT_FOUND, "未找到对应的店铺信息")));
                return;
            }
            Integer shopId = shop.getId();
        String path = req.getPathInfo();
        System.out.println("[MerchantServlet.doPut] 收到PUT请求: " + path);

        // 获取当前登录的客户用户
        User MerchantUserUser = (User) session.getAttribute("user");
        System.out.println("MerchantServlet.doPut] 当前用户信息: " + (MerchantUserUser != null ? "ID=" + MerchantUserUser.getId() : "未登录"));

        // 先处理特殊路径，修复路径匹配问题
        if (pathInfo == null || pathInfo.trim().isEmpty()) {
            System.out.println("[MerchantServlet.doPut] 路径为空");
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "请求路径不能为空")));
            return;
        }

        switch (pathInfo) {
            case "/shop/update":
                // 更新店铺信息
                handleShopUpdate(req, resp, shopId);
                return;
            case "/room/type/update":
                // 更新房型
                handleUpdateRoomType(req, resp);
                return;

            default:
                // 未知路径
                System.out.println("[MerchantServlet.doPut] 未知路径: " + pathInfo);
                resp.getWriter().write(gson.toJson(Result.failure(ResultCode.NOT_FOUND, "未知操作：" + pathInfo)));
        }
    } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 处理店铺注册请求
     */
    private void handleShopRegister(HttpServletRequest req, HttpServletResponse resp, User user) throws IOException {
        // 获取当前登录的商户用户
        HttpSession session = req.getSession(false);
        if (session == null || user == null) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.UNAUTHORIZED, "请先登录")));
            return;
        }

        // 获取店铺信息
        String shopName = req.getParameter("shopname");
        String address = req.getParameter("address");
        String contact = req.getParameter("contact");
        String keywords = req.getParameter("keywords");
        String status = req.getParameter("status");

        // 验证必要参数
        if (shopName == null || address == null || contact == null ||
                shopName.trim().isEmpty() || address.trim().isEmpty() || contact.trim().isEmpty()) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺名称、地址和联系方式不能为空")));
            return;
        }

        // 验证店铺名称长度
        if (shopName.length() > 50) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺名称不能超过50个字符")));
            return;
        }

        // 验证联系方式格式
        if (!contact.matches("^1[3-9]\\d{9}$")) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "联系方式格式不正确，请输入11位手机号")));
            return;
        }

        try {
            // 创建Shop对象
            Shop shop = new Shop();
            shop.setShopname(shopName);
            shop.setAddress(address);
            shop.setContact(contact);
            shop.setKeywords(keywords != null ? keywords : "");
            shop.setStatus(status != null ? status : "open");

            // 调用控制器注册店铺
            Result<Shop> result = merchantController.register(shop, user.getId());
            if (!result.isSuccessful()){
                System.out.println("店铺注册失败：" + result.getMessage());
            }
            resp.getWriter().write(gson.toJson(result));
        } catch (Exception e) {
            System.out.println("店铺注册异常：" + e.getMessage());
            e.printStackTrace();
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.SYSTEM_ERROR, "店铺注册失败：" + e.getMessage())));
        }
    }

    /**
     * 处理更新店铺信息请求
     */
    private void handleShopUpdate(HttpServletRequest req, HttpServletResponse resp, Integer shopId) throws IOException {
        System.out.println("[MerchantServlet.handleShopUpdate] 开始处理店铺更新请求");
        System.out.println("[MerchantServlet.handleShopUpdate] 店铺ID: " + shopId);

        // 读取前端传来的JSON数据
        StringBuilder sb = new StringBuilder();
        String line;
        try (java.io.BufferedReader reader = req.getReader()) {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        String json = sb.toString();
        System.out.println("[MerchantServlet.handleShopUpdate] 接收到的JSON: " + json);

        // 获取原有店铺信息
        Shop originalShop = merchantController.getShopByUserId(((User)req.getSession().getAttribute("user")).getId()).getData();
        if (originalShop == null) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.NOT_FOUND, "未找到对应的店铺信息")));
            return;
        }

        // 反序列化JSON为Shop对象
        Shop shopFromJson = null;
        try {
            shopFromJson = gson.fromJson(json, Shop.class);
        } catch (Exception e) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "JSON格式错误")));
            return;
        }

        // 字段合并：如果前端没有传某字段，则用原有值
        Shop shop = new Shop();
        shop.setId(shopId);
        shop.setShopname(shopFromJson.getShopname() != null ? shopFromJson.getShopname() : originalShop.getShopname()); // 店铺名
        shop.setAddress(shopFromJson.getAddress() != null ? shopFromJson.getAddress() : originalShop.getAddress()); // 地址
        shop.setContact(shopFromJson.getContact() != null ? shopFromJson.getContact() : originalShop.getContact()); // 联系方式
        shop.setKeywords(shopFromJson.getKeywords() != null ? shopFromJson.getKeywords() : originalShop.getKeywords()); // 关键词
        shop.setStatus(shopFromJson.getStatus() != null ? shopFromJson.getStatus() : originalShop.getStatus()); // 状态
        // 合并审核状态
        shop.setAuditStatus(shopFromJson.getAuditStatus() != null ? shopFromJson.getAuditStatus() : originalShop.getAuditStatus()); // 如果前端未传，则用原有值
        // 合并销量
        shop.setSalesVolume(shopFromJson.getSalesVolume() != null ? shopFromJson.getSalesVolume() : originalShop.getSalesVolume()); // 如果前端未传，则用原有值
        // 合并发布时间
        shop.setPublishTime(shopFromJson.getPublishTime() != null ? shopFromJson.getPublishTime() : originalShop.getPublishTime()); // 如果前端未传，则用原有值
        // 合并营业额
        shop.setRevenue(shopFromJson.getRevenue() != null ? shopFromJson.getRevenue() : originalShop.getRevenue()); // 如果前端未传，则用原有值
        // 合并userId
        shop.setUserId(shopFromJson.getUserId() != null ? shopFromJson.getUserId() : originalShop.getUserId()); // 如果前端未传，则用原有值
        // 合并收藏量
        shop.setFavoritesVolume(shopFromJson.getFavoritesVolume() != 0 ? shopFromJson.getFavoritesVolume() : originalShop.getFavoritesVolume()); // 如果前端未传，则用原有值
        // 合并浏览量
        shop.setViewCount(shopFromJson.getViewCount() != null ? shopFromJson.getViewCount() : originalShop.getViewCount()); // 如果前端未传，则用原有值

        System.out.println("[MerchantServlet.handleShopUpdate] 最终用于更新的完整店铺信息: " + shop);

        // 参数验证
        if (shop.getShopname() == null || shop.getShopname().trim().isEmpty()) {
            System.out.println("[MerchantServlet.handleShopUpdate] 店铺名称为空");
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "店铺名称不能为空")));
            return;
        }

        // 调用控制器更新店铺信息
        Result<Shop> result = merchantController.updateShopInfo(shopId, shop);
        System.out.println("[MerchantServlet.handleShopUpdate] 更新结果: " + result);

        resp.getWriter().write(gson.toJson(result));
    }

    /**
     * 处理添加房型请求
     */
    private void handleAddRoomType(HttpServletRequest req, HttpServletResponse resp, Integer shopId) throws IOException {
        // 获取房型信息
        String typeName = req.getParameter("typeName");
        BigDecimal price = new BigDecimal(req.getParameter("price"));
        Integer stock = Integer.parseInt(req.getParameter("stock"));
        String bedType = req.getParameter("bedType");

        // 创建RoomType对象
        RoomType roomType = new RoomType();
        roomType.setShopId(shopId);
        roomType.setTypeName(typeName);
        roomType.setPrice(price);
        roomType.setStock(stock);
        roomType.setBedType(bedType);

        // 调用控制器添加房型
        Result<RoomType> result = merchantController.addRoomType(roomType);
        resp.getWriter().write(gson.toJson(result));
    }

    /**
     * 处理更新房型请求
     */
    private void handleUpdateRoomType(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取当前登录的商户用户
        HttpSession session = req.getSession();
        User merchantUser = (User) session.getAttribute("user");
        
        // 获取店铺信息
        Shop shop = merchantController.getShopByUserId(merchantUser.getId()).getData();
        if (shop == null) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.NOT_FOUND, "未找到对应的店铺信息")));
            return;
        }
        Integer shopId = shop.getId();

        // 读取前端传来的JSON数据
        StringBuilder sb = new StringBuilder();
        String line;
        try (java.io.BufferedReader reader = req.getReader()) {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        String json = sb.toString();
        System.out.println("[MerchantServlet.handleUpdateRoomType] 接收到的JSON: " + json);

        // 反序列化JSON为RoomType对象
        RoomType roomTypeFromJson = null;
        try {
            roomTypeFromJson = gson.fromJson(json, RoomType.class);
        } catch (Exception e) {
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.PARAM_ERROR, "JSON格式错误")));
            return;
        }

        // 获取原有的房型信息
        List<RoomType> existingRoomTypes = merchantController.getRoomTypes(shopId).getData();
        RoomType originalRoomType = null;
        System.out.println("[MerchantServlet.handleUpdateRoomType] 开始查找房型，ID: " + roomTypeFromJson.getId());
        for (RoomType rt : existingRoomTypes) {
            System.out.println("[MerchantServlet.handleUpdateRoomType] 比较房型ID: " + rt.getId() + " 与 " + roomTypeFromJson.getId());
            if (rt.getId() == roomTypeFromJson.getId()) {
                originalRoomType = rt;
                System.out.println("[MerchantServlet.handleUpdateRoomType] 找到匹配的房型");
                break;
            }
        }

        if (originalRoomType == null) {
            System.out.println("[MerchantServlet.handleUpdateRoomType] 未找到对应的房型信息");
            resp.getWriter().write(gson.toJson(Result.failure(ResultCode.NOT_FOUND, "未找到对应的房型信息")));
            return;
        }

// 创建新的RoomType对象，合并原有数据和新的数据
        RoomType roomType = new RoomType();
        roomType.setId(roomTypeFromJson.getId());
        roomType.setShopId(shopId);
        roomType.setTypeName(roomTypeFromJson.getTypeName() != null ? roomTypeFromJson.getTypeName() : originalRoomType.getTypeName());
        roomType.setPrice(roomTypeFromJson.getPrice() != null ? roomTypeFromJson.getPrice() : originalRoomType.getPrice());
        roomType.setStock(originalRoomType.getStock());  // 保持原有库存不变
        roomType.setBedType(roomTypeFromJson.getBedType() != null ? roomTypeFromJson.getBedType() : originalRoomType.getBedType());

        System.out.println("[MerchantServlet.handleUpdateRoomType] 准备更新的房型信息: " + roomType);

        // 调用控制器更新房型
        Result<RoomType> result = merchantController.updateRoomType(roomType.getId(), roomType);
        resp.getWriter().write(gson.toJson(result));
    }

    /**
     * 处理删除房型请求
     */
    private void handleDeleteRoomType(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取房型ID
        Integer roomTypeId = Integer.parseInt(req.getParameter("roomTypeId"));

        // 调用控制器删除房型
        Result<Void> result = merchantController.deleteRoomType(roomTypeId);
        resp.getWriter().write(gson.toJson(result));
    }

    /**
     * 处理核销订单请求
     */
    private void handleVerifyOrder(HttpServletRequest req, HttpServletResponse resp, Integer merchantId) throws IOException {
        // 获取订单ID
        Integer orderId = Integer.parseInt(req.getParameter("orderId"));

        // 调用控制器核销订单
        Result<Order> result = merchantController.verifyOrder(orderId, merchantId);
        resp.getWriter().write(gson.toJson(result));
    }

    /**
     * 处理退订申请请求
     */
    private void handleProcessRefund(HttpServletRequest req, HttpServletResponse resp, Integer shopId) throws IOException {
        // 获取订单ID和审批结果
        Integer orderId = Integer.parseInt(req.getParameter("orderId"));
        boolean approved = Boolean.parseBoolean(req.getParameter("approved"));

        // 调用控制器处理退订申请
        Result<Order> result = merchantController.processRefund(orderId, shopId, approved);
        resp.getWriter().write(gson.toJson(result));
    }

    /**
     * 处理添加用户到黑名单请求
     */
    private void handleAddToBlacklist(HttpServletRequest req, HttpServletResponse resp, Integer shopId) throws IOException {
        Integer userId = Integer.parseInt(req.getParameter("userId"));

        // 调用控制器添加用户到黑名单
        Result<Void> result = merchantController.addUserToBlacklist(shopId, userId);
        resp.getWriter().write(gson.toJson(result));
    }

    /**
     * 处理从黑名单中移除用户请求
     */
    private void handleRemoveFromBlacklist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 获取黑名单记录ID
        Integer blacklistId = Integer.parseInt(req.getParameter("blacklistId"));

        // 调用控制器从黑名单中移除用户
        Result<Void> result = merchantController.removeUserFromBlacklist(blacklistId);
        resp.getWriter().write(gson.toJson(result));
    }
}
